// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init({
    env: 'dragondaily-nstam'
});

const db = cloud.database();

const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
    const { openID, appID } = cloud.getWXContext(); // 这里获取到的 openId 和 appId 是可信的
    const { targetID } = event;
    const messageBoardCollection = db.collection('messageboard');
    const messageShareLogCollection = db.collection('message_share_log');

    let queryResult;

    queryResult = await messageBoardCollection.where({
        _id: targetID
    }).get();

    if (queryResult.data.length === 0) {
        return {
            status: 'fail',
            message: '没有该条留言'
        };
    }

    const likeData = {
        openID: openID,
        appID: appID,
        targetID: targetID
    };

    queryResult = await messageShareLogCollection.where(likeData).get();

    if (queryResult.data.length > 0) {
        return {
            status: 'fail',
            message: '已经分享过了'
        };
    }

    const addResult = await messageShareLogCollection.add({
        data: likeData
    });

    if (!addResult._id) {
        return {
            status: 'fail',
            message: '分享失败'
        };
    }

    await messageBoardCollection.where({
        _id: targetID
    }).update({
        data: {
            shareCount: _.inc(1)
        }
    });

    return {
        status: 'success'
    };
};
